package sit.engreal.leetcode.problems100;

import java.util.HashMap;

import static org.junit.jupiter.api.Assertions.*;

/**
 * <a href="https://leetcode.cn/problems/roman-to-integer/"> 13. 罗马数字转整数 </a>
 */
public class LeetCode13 {
    static class Solution {
        static final HashMap<Character, Integer> map = new HashMap<>();

        static {
            map.put('I', 1);
            map.put('V', 5);
            map.put('X', 10);
            map.put('L', 50);
            map.put('C', 100);
            map.put('D', 500);
            map.put('M', 1000);
        }

        public int romanToInt(String s) {
            int n = 0;
            int x = Integer.MAX_VALUE;
            for (int i = 0; i < s.length(); i++) {
                int y = map.get(s.charAt(i));
                n += y;
                if (y > x) {
                    n -= (2 * x);
                }
                x = y;
            }
            return n;
        }
    }

    public static void main(String[] args) {


        final Solution solution = new Solution();

        assertEquals(3, solution.romanToInt("III"));
        assertEquals(4, solution.romanToInt("IV"));
        assertEquals(9, solution.romanToInt("IX"));
        assertEquals(58, solution.romanToInt("LVIII"));
        assertEquals(1994, solution.romanToInt("MCMXCIV"));
    }
}
